<?php
class App_Module_Admin_Component_Cfg_Ctrl_Http_Web extends Mozg_Controller_Instance
{
	private $_id;
	private $_idParts = array();

	protected $_paramsFieldName = 'data';

    protected function PrimaryActionInit ($basicActionName)
    {
    	$key = $this->GetQueryIdParts(0);
		Mozg::Layout('admin')->SetMenuActiveElement('cfg/cfg_' . $key);
    }

    public function GetQueryId()
    {
    	if ($this->_id !== null) return $this->_id;

		$this->_id = Mozg::Request('http')->get('id');
		$this->_idParts = explode('/', $this->_id);
		
		$fields = Mozg_Cfg::Get('admin/cfg')->GetCategories();
		for ($i=0; $i<sizeof($this->_idParts); $i++)
		{
			if (!isset($fields[$this->_idParts[$i]]))
			{
				$fieldsKeys = array_keys($fields);
				$this->_idParts[$i] = $fieldsKeys[0];
			}
			
			$fields = $fields[$this->_idParts[$i]]['subcfg'];
		}
		
		$this->_id = implode('/', $this->_idParts);
		
		return $this->_id;
    }
    
    public function GetQueryIdParts($key = false)
    {
    	$this->GetQueryId();
    	
    	if (false === $key) return $this->_idParts;
    	return isset($this->_idParts[$key]) ? $this->_idParts[$key] : false;
    }

	protected function GetParamsPath($id)
	{
		$parts = explode('/', $id);
		$field = array_pop($parts);
		
		$fields = Mozg_Cfg::Get('admin/cfg')->GetCategories();
		if (sizeof($parts))
		{
			foreach ($parts as $part)
			{
				$fields = $fields[$part]['subcfg'];
			}
		}

		return $fields[$field]['fieldparams'];
	}

	/**
		экшен по-умолчанию
	*/
    public function PrAction ()
    {
        $this->listPr();
    }
    
    public function savePrAction ()
    {
    	$id = $this->GetQueryId();
    	$config = Mozg_Cfg::Get($this->GetParamsPath($id));
    	
    	$data = (array)Mozg::Request('http')->getPost('data');

		$this->GetTpl('Web')->SetPostData($config, $data);
    	
		if (Mozg_Cfg::Save($this->GetParamsPath($id)))
		{
			Mozg::Lib('messanger')->createMessage(Mozg_Lang::_('CONFIG_SAVED'));
		}
		else
		{
			Mozg::Lib('messanger')->createMessage(Mozg_Lang::_('CONFIG_SAVE_ERROR'), MESSAGE_ERROR);
		}
		
        Mozg_Router::Get('http')->Redirect(array('module' => 'admin', 'ctrl' => 'cfg', 'action' => 'list', 'id' => $id));
    }
    
    public function listPrAction ()
    {
    	$id = $this->GetQueryId();
    	
        $t = $this->GetTpl('Web');
        Mozg::Response('http')->SetBody($t->OutCfg($id, Mozg_Cfg::Get($this->GetParamsPath($id))));

        Mozg::SubAction()->Set('Left Sidebar', array($this, 'OutCfgSubmenu'));
    }

    public function OutCfgSubmenu()
    {
    	$fields = Mozg_Cfg::Get('admin/cfg')->GetCategories();
    	
    	if (!isset($fields[$this->GetQueryIdParts(0)]['subcfg'])) return '';
    	
		$subFields = $fields[$this->GetQueryIdParts(0)]['subcfg'];
    	if (!sizeof($subFields)) return '';
		
        $t = $this->GetTpl('Web');
        return $t->SubmenuBlock($this->GetQueryId(), $this->GetQueryIdParts(), $subFields);
    }
}